package org.helgoboss.commandlet_http_provider_tray

import org.osgi.framework.{BundleActivator, BundleContext}
import org.helgoboss.osgi_additions.{OsgiLogging, OsgiContext, OsgiServiceWatcher}
import java.awt.{Desktop, SystemTray, TrayIcon, Toolkit}
import org.helgoboss.commandlet_http_provider.CommandletHttpProvider
import java.net.URL
import java.awt.event.{MouseAdapter, MouseListener, MouseEvent}

object CommandletHttpProviderTray {
    val PathToIcons = "/org/helgoboss/commandlet_http_provider_tray/icons"
    val PathToOnIcon = PathToIcons + "/on.png"
    val PathToOffIcon = PathToIcons + "/off.png"
    val TooltipText = "Commandlet HTTP Provider"
    val WebConsoleUrlContextPath = "/system/console"
    
}

class CommandletHttpProviderTray extends OsgiContext with OsgiLogging with OsgiServiceWatcher {
    
    import CommandletHttpProviderTray._
    
    private var trayIcon: TrayIcon = _
    
        
    whenBundleActive {
        /* TODO: Make system tray a service and watch it */
        if (SystemTray.isSupported) {
            val image = getImage(PathToOffIcon)
            trayIcon = new TrayIcon(image, TooltipText)
            trayIcon.setImageAutoSize(true)
            SystemTray.getSystemTray.add(trayIcon)
            var mouseListener: MouseListener = null
            
            whenServicePresent[CommandletHttpProvider] { httpProvider =>
                onStart {
                    changeTrayIconImage(PathToOnIcon)
                        
                    /* Make button double click on tray icon open web console in browser */
                    
                    mouseListener = new MouseAdapter {
                        override def mouseClicked(e: MouseEvent) {
                            if (e.getClickCount == 2 && Desktop.isDesktopSupported && Desktop.getDesktop.isSupported(Desktop.Action.BROWSE)) {
                                Desktop.getDesktop.browse(new URL("http://localhost:" + httpProvider.port + WebConsoleUrlContextPath).toURI)
                            }
                        }
                    }
                    trayIcon.addMouseListener(mouseListener)
                }
                onStop {
                    changeTrayIconImage(PathToOffIcon)
                    trayIcon.removeMouseListener(mouseListener)
                }
            }
            onStop {
                SystemTray.getSystemTray.remove(trayIcon)
                trayIcon.getImage.flush
                trayIcon = null
            }
        }
    }
    
	    
    private def getImage(pathToIcon: String) = {
        Toolkit.getDefaultToolkit.getImage(bundleContext.getBundle.getResource(pathToIcon))
    }
    
    private def changeTrayIconImage(pathToIcon: String) {
        trayIcon.getImage.flush
        trayIcon.setImage(getImage(pathToIcon))
    }
}



